package com.tutu.order.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tutu.commons.clients.ProductClient;
import com.tutu.commons.pojo.Order;
import com.tutu.commons.to.OrderToProduct;
import com.tutu.commons.utils.R;
import com.tutu.commons.vo.CartVo;
import com.tutu.commons.vo.OrdersVo;
import com.tutu.order.mapper.OrderMapper;
import com.tutu.order.service.OrderService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Program: b2c-cloud-store
 * @Description:
 * @Author: JK.TuTu
 * @Version: 1.0
 * @Create: 2022-12-27 17:15
 **/
@Service
@Transactional
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductClient productClient;


    /**
     * 生成订单接口
     *
     * @param ordersVo (用户id,购物车Vo)
     * @return 返回结果实体对象
     */
    @Override
    public R saveOrder(OrdersVo ordersVo) {
        //保存订单数据
        List<Order> ordersList = new ArrayList<>();
        //保存购物车Id
        List<Integer> cartIds = new ArrayList<>();
        //保存订单服务发送给商品服务的实体类
        List<OrderToProduct> orderToProducts = new ArrayList<>();
        //使用UUID生成订单号
        String orderId = IdUtil.simpleUUID();

        for (CartVo cartVo : ordersVo.getProducts()) {
            //获取保存到订单的数据
            Order order = new Order();
            order.setOrderId(orderId);
            order.setUserId(ordersVo.getUserId());
            order.setProductId(cartVo.getProductId());
            order.setProductNum(cartVo.getNum());
            order.setProductPrice(cartVo.getPrice());
            ordersList.add(order);
            //获取传递给购物车服务的数据
            cartIds.add(cartVo.getId());
            //获取传递给商品服务的数据
            OrderToProduct orderToProduct = new OrderToProduct();
            orderToProduct.setProductId(cartVo.getProductId());
            orderToProduct.setNum(cartVo.getNum());
            orderToProducts.add(orderToProduct);
        }
        try {
            //批量保存到订单
            this.saveBatch(ordersList);
            //发送数据给购物车服务
            rabbitTemplate.convertAndSend("topic.ex", "clear.cart", cartIds);
            //发送数据给商品服务
            rabbitTemplate.convertAndSend("topic.ex", "sub.number", orderToProducts);
            return R.ok("购买成功!");

        } catch (Exception e) {
            e.printStackTrace();
            return R.fail("购买失败!");
        }

    }


    /**
     * 根据用户id查看订单
     * TODO
     *
     * @param userId 用户id
     * @return 返回结果是实体类
     */
    @Override
    public R getOrders(Integer userId) {
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Order::getUserId, userId);
        List<Order> orders = orderMapper.selectList(queryWrapper);

        orders.stream().forEach(order -> {
            R result = productClient.getProductId(order.getProductId());
            LinkedHashMap<String, Object> productMap = (LinkedHashMap<String, Object>) result.getData();
            //获取商品的图片路径
            String productPicture = productMap.get("productPicture").toString();
            order.setProductPicture(productPicture);
        });
        //根据订单ID分组  封装成Map
        Map<String, List<Order>> orderMap = orders.stream().collect(Collectors.groupingBy(Order::getOrderId));
        //封装返回结果
        List<List<Order>> result = new ArrayList<>();
        //将Map集合中的List<Order>放到封装的结果中
        result.addAll(orderMap.values());
        return R.ok(result);
    }
}
